﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Storage.Pickers;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Popups;
using Windows.UI.Xaml.Media.Imaging;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class quizBuilder1 : StudyTime_1.Common.LayoutAwarePage
    {

        public List<quizQuest> quizList = new List<quizQuest>();
        private bool saveLocation = false;
        private string filePath;
        private string fileName = "goo.xml";
        private StorageFile storage;
        private StorageFile tempStorage;
        private byte[] img;
        private Stream outStream;
        private DataContractSerializer xml;
        private bool showMessage = false;
        private bool quizLoaded = false;
        private byte[] badImg = new byte[1];
        BitmapImage badBImage;

        public quizBuilder1()
        {
            this.InitializeComponent();
            answer.ItemsSource = new List<string> { "A", "B", "C", "D" };

            if (App.fromManager == true)
            {
                loadFromManager();
            }
            
        }


        async public void loadFromManager()
        {
          await classes.serializer.load(false);

          questCounter.Text = App.quizList.Count.ToString();

          App.fromManager = false;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        async private void loadData(List<quizQuest> quiz)
        {

            //convLength = 0;

            quizList.Clear();
           
            {

                StorageFolder storageFolder = KnownFolders.VideosLibrary;



                {
                    try
                    {
                        errorBox.Text = fileName;
                        //Opens the text file that the array is stored in.
                        // storage = await storageFolder.GetFileAsync(filePath);




                         xml = new DataContractSerializer(typeof(List<quizQuest>));

                        var file = await storage.OpenAsync(FileAccessMode.Read);
                        Stream inStream = file.AsStreamForRead();

                        quiz = xml.ReadObject(inStream) as List<quizQuest>;

                        foreach (quizQuest quizQuest in quiz)
                        {
                            quizList.Add(quizQuest);
                        }


                        if (showMessage == false)
                        {
                            var mDialog = new MessageDialog("Since you opened a file, adding a quiz will append to the opened file, there is no need to save again. But the button remains for your comfort.");
                            await mDialog.ShowAsync();
                            showMessage = true;
                            quizLoaded = true;
                            //saveAll.IsEnabled = true;
                            
                        }
                        else
                        {
                        }

                   
                    }
                    catch (IOException)
                    {

                    }
                }
            }
        }

        async public void openSelected()
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            openPicker.FileTypeFilter.Add(".quizxml");


            storage = await openPicker.PickSingleFileAsync();

            if (null != storage)
            {
                // Application now has read/write access to the picked file
                fileName = storage.Name;
                filePath = storage.Path;
                loadData(quizList);
                //questions.Text = fileName + " Click Load if this is the correct File";

            }
            else
            {
                errorBox.Text = "File was not returned";
            }
        }

        async public void selection()
        {

            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.Downloads;
            savePicker.SuggestedFileName = "quiz1";
            savePicker.DefaultFileExtension = ".quizxml";
            savePicker.FileTypeChoices.Add("QUIZ", new List<string>() { ".quizxml" });
            storage = await savePicker.PickSaveFileAsync();

            if (null != storage)
            {
                // Application now has read/write access to the picked file
                tempStorage = storage;
                filePath = storage.Path;
                fileName = storage.Name;
                saveLocation = true;
                
                SerializeXML(quizList);

            }
            else
            {
                storage = tempStorage;
                errorBox.Text = "File was not returned";
            }
        }

        async private void SerializeXML(List<quizQuest> convert)
        {

            try
            {
                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                Stream outStream = file.AsStreamForWrite();



                xml = new DataContractSerializer(typeof(List<quizQuest>));


                xml.WriteObject(outStream, convert);

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }

        //adds a quiz question
       async private void Button_Click_1(object sender, RoutedEventArgs e)
        {

            if (App.quizFile == null)
            {

                await openHelper.savePicker(false);

                await classes.messages.setMssg("quiz");

                if (multQuest.Text != "" && answerB.Text != "")
                {


                    classes.quizAct.addQuiz(multQuest.Text, answer.SelectedItem.ToString(), answerA.Text, answerB.Text,
                        answerC.Text, answerD.Text, img);
                }
            }
            else
            {


                if (multQuest.Text != "" && answerB.Text != "" && answer.SelectedItem != null)
                {

                    classes.quizAct.addQuiz(multQuest.Text, answer.SelectedItem.ToString(), answerA.Text, answerB.Text,
                        answerC.Text, answerD.Text, img);
                }
            }

            //try
            //{
            //    quizQuest quest = new quizQuest();
            //    quest.question = multQuest.Text.ToString();
            //    quest.answerA = answerA.Text.ToString();
            //    quest.answerB = answerB.Text.ToString();
            //    quest.answerC = answerC.Text.ToString();
            //    quest.answerD = answerD.Text.ToString();
            //    quest.answer = answer.SelectedItem.ToString();
            //    quest.picture = img;

            //    quizList.Add(quest);

            //    errorBox.Text = quizList.Count.ToString() + " " + "Items Added";
            //    answerA.Text = "";
            //    answerB.Text = "";
            //    answerC.Text = "";
            //    answerD.Text = "";

            //    multQuest.Text = "";

            //    setBlankImage();


            //    if (saveLocation == true || quizLoaded == true)
            //    {
            //        append(quizList);
            //    }
            //    else
            //    {
            //        saveAll.IsEnabled = true;
            //    }
            //}
            //catch
            //{
            //}

            questCounter.Text = (App.quizList.Count - 1).ToString();

            answerA.Text = "";
            answerB.Text = "";
            answerC.Text = "";
            answerD.Text = "";

            multQuest.Text = "";

            setBlankImage();
          



        }

        async private void append(List<quizQuest> convert)
        {
            try
            {
                var file = await storage.OpenAsync(FileAccessMode.ReadWrite);
                outStream = file.AsStreamForWrite();

                xml.WriteObject(outStream, convert);

                await outStream.FlushAsync();
                file.Dispose();

                errorBox.Text = "Saved Successfully!";
            }
            catch (IOException)
            {
                errorBox.Text = "Cannot write to the file";
            }

        }



       //async private void saveAll_Click(object sender, RoutedEventArgs e)
       // {

       //     if (showMessage == false)
       //     {
       //         var mDialog = new MessageDialog("You only need to export once. After first export each added item will be appended to the saved file.");
       //         await mDialog.ShowAsync();
       //         showMessage = true;
       //     }
       //     else
       //     {
       //     }
       //     selection();




       // }

        private void back_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.GoBack();
        }

        private void pageRoot_Loaded(object sender, RoutedEventArgs e)
        {
            //saveAll.IsEnabled = false;

            Storyboard sb = this.FindName("quizBuilderStory") as Storyboard;
            if (sb != null)
            {
                sb.Begin();
            }
        }

       async private void addImage_Click(object sender, RoutedEventArgs e)
        {


            await classes.getImg.getImage();


            img = classes.getImg.getArray();

            insertPreview.Source = classes.getImg.getPicture();

            //FileOpenPicker openPicker = new FileOpenPicker();
            //openPicker.ViewMode = PickerViewMode.List;
            //openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            //openPicker.FileTypeFilter.Add(".jpg");
            //openPicker.FileTypeFilter.Add(".jpeg");
            //openPicker.FileTypeFilter.Add(".png");
            //openPicker.FileTypeFilter.Add(".bmp");
            //storage = await openPicker.PickSingleFileAsync();

            //if (null != storage)
            //{

            //    var file = await storage.OpenAsync(FileAccessMode.Read);

            //    Stream inStream = file.AsStreamForRead();

            //     BitmapImage tmpImg = new BitmapImage();

            //    using (MemoryStream br = new MemoryStream())
            //    {
                   
            //        inStream.CopyTo(br);
            //        img = br.ToArray();

                   
                    
                    
            //    }

                

            //var stream = new InMemoryRandomAccessStream();

            //using (var writer = new DataWriter(stream))
            //{
                
            //        writer.WriteBytes(img);
            //        await writer.StoreAsync();
            //        writer.DetachStream();
                  
              
            //}
            //    stream.Seek(0);
            //    tmpImg.SetSource(stream);
            
            //    insertPreview.Source = tmpImg;
           
            //   await stream.FlushAsync();
        
               

            //    errorBox.Text = "Image Loaded.";

            //}
            //else
            //{
            //    errorBox.Text = "File was not returned";
            //}

        }

      async private void openDeck_Click(object sender, RoutedEventArgs e)
       {

           //openSelected();

         
               await openHelper.openPicker(false);
          
          

          //await classes.serializer.load(true);

               if (App.quizFile != null && App.quizList.Count > 0)
               {

                   questCounter.Text = (App.quizList.Count - 1).ToString();

                   await classes.messages.setMssg("quiz");
               }

       }

       async private void setBlankImage()
       {
           //byte[] tmp = new byte[1]; 
            byte[] blank = new byte[1];

            img = null;

              
            

            BitmapImage tmpImg = new BitmapImage();

            var stream = new InMemoryRandomAccessStream();

            using (var writer = new DataWriter(stream))
            {
                
                    writer.WriteBytes(blank);
                    await writer.StoreAsync();
                    writer.DetachStream();
                    //imagebttn.IsEnabled = false;
                
            }
            stream.Seek(0);
            tmpImg.SetSource(stream);
            
            insertPreview.Source = tmpImg;
           
           await stream.FlushAsync();
        }

        private void rmvAd_Click(object sender, RoutedEventArgs e)
       {

           removeAds.setNofication();
           //MessageDialog startDialog = new MessageDialog("If you do not want to see ads again please select Go To Store, otherwise press cancel", "Remove Ads?");
           //UICommand store = new UICommand("Go To Store", onStore);
           //UICommand cancel = new UICommand("Cancel");

           //startDialog.Commands.Add(store);
           //startDialog.Commands.Add(cancel);

           //await startDialog.ShowAsync();
       }

        

        private void lstQuestion_Click(object sender, RoutedEventArgs e)
        {



            int count = App.quizList.Count - 1;

            if (count >= 0)
            {

                lastQuestTxt.Text = App.quizList[count].question.ToString() + Environment.NewLine + Environment.NewLine + "A: " + App.quizList[count].answerA + Environment.NewLine + Environment.NewLine + "B: " +
                            App.quizList[count].answerB + Environment.NewLine + Environment.NewLine + "C: " + App.quizList[count].answerC +
                            Environment.NewLine + Environment.NewLine + "D: " + App.quizList[count].answerD + Environment.NewLine + Environment.NewLine + "Answer: " + App.quizList[count].answer;
                //setImage(currPage, false);

                lastQuestStack.Visibility = Visibility.Visible;
            }

        }

        private void pageRoot_Tapped(object sender, TappedRoutedEventArgs e)
        {

            //if (lastQuestStack.Visibility == Visibility.Visible)
            //{
            //    lastQuestStack.Visibility = Visibility.Collapsed;
            //}

        }

        private void stackBack_Click(object sender, RoutedEventArgs e)
        {
            if (lastQuestStack.Visibility == Visibility.Visible)
            {
                lastQuestStack.Visibility = Visibility.Collapsed;
            }
        }

     

       //async public void onStore(object command)
       //{
       //    Uri pageUri = new Uri("http://apps.microsoft.com/webpdp/app/study-time/ee4a5766-52ff-471d-b743-3ecd3157eee7");
       //    await Windows.System.Launcher.LaunchUriAsync(pageUri);

       //}
    
               


       }

    }

